package router

import (
	"alarm_service/common/client_conn"
	"alarm_service/common/logger"
	"alarm_service/internal/api"
	"bytes"
	"fmt"
	"io"
	"net"
	"time"
)

const prefix byte = 0x53
const suffix byte = 0x45

const CmdPhonePack byte = 0x41
const CmdMsgSwitchPack byte = 0x42
const CmdResetPack byte = 0x43
const CmdIccidPack byte = 0x44
const CmdPhoneSwitchPack byte = 0x45
const CmdInfoPack byte = 0x47
const CmdHeartBeatPack byte = 0x48

type TcpRouter struct {
	TcpApi     *api.TcpApi
	CommandApi *api.CommandApi
}

func NewTcpRouter(tcpApi *api.TcpApi, commandApi *api.CommandApi) *TcpRouter {
	return &TcpRouter{
		TcpApi:     tcpApi,
		CommandApi: commandApi,
	}
}

func (s *TcpRouter) HandleTcpConnection(conn net.Conn) {
	defer conn.Close()
	defer func() {
		if err := recover(); err != nil {
			logger.Infof("[HandleTcpConnection] error: %v", err)
		}
	}()
	buffer := make([]byte, 1024)
	data := []byte{}
	for {
		n, err := conn.Read(buffer)
		// message, err := buffer.Rede('\n')
		fmt.Printf("接收到 %d 字节的数据: %s\n", n, string(buffer[:n]))
		if err != nil {
			if err == io.EOF {
				logger.Info("[TCP] Connection closed by client.")
			} else {
				logger.Infof("[TCP] Error reading from connection: %v\n", err)
			}
			logger.Infof("[TCP] Client disconnected: %s", err.Error())
			s.TcpApi.OnTcpCloseHandler(conn)
			client_conn.Remove(conn)
			return
		}

		logger.Infof("测试 message 16: %x", string(buffer[:n]))

		data = append(data, buffer[:n]...)
		t := string(data)
		// bytes, err := hex.DecodeString(t)
		// fmt.Println(bytes)

		bytes := []byte(t)
		// for i := 0; i < len(t); i += 2 {
		// 	// 解析每两个字符为一个字节
		// 	byteValue, err := hex.DecodeString(t[i : i+2])
		// 	if err != nil {
		// 		logger.Infof("位置 %d 处的字符无法解析为十六进制: %v", i, err)
		// 	}
		// 	bytes[i/2] = byteValue[0]
		// }
		s.processData(&bytes, conn)
		time.Sleep(2 * time.Second)
		// Echo the message back to the client
		//_, err2 := conn.Write(buffer[:n])
		//logger.Infof("Send message %x", buffer[:n])
		//if err2 != nil {
		//	logger.Error("Error writing to connection: %v", err)
		//	return
		//}
	}
}

func (s *TcpRouter) processData(data *[]byte, conn net.Conn) {
	for {
		index := bytes.IndexByte(*data, suffix)
		if index == -1 {
			return
		}

		packet := (*data)[:index]

		*data = (*data)[index+1:]

		if packet[0] != prefix {
			logger.Infof("Packet not prefix error: %x", packet)
			return
		}
		spacket := packet[2:]
		switch packet[1] {
		case CmdPhonePack:
			s.TcpApi.OnPhoneCallBackHandler(spacket, conn)
		case CmdMsgSwitchPack:
			s.TcpApi.OnMsgSwitchCallBackHandler(spacket, conn)
		case CmdResetPack:
			s.TcpApi.OnResetCallBackHandler(spacket, conn)
		case CmdIccidPack:
			logger.Infof("Received packet CmdResetPack: %s", packet)
		case CmdPhoneSwitchPack:
			s.TcpApi.OnPhoneSwitchCallBackHandler(spacket, conn)
		case CmdHeartBeatPack:
			s.TcpApi.OnHeartBeatHandler(spacket, conn)
		case CmdInfoPack:
			s.TcpApi.OnInfoHandler(spacket, conn)
		default:
			logger.Infof("Received packet default: %s", packet)
		}
	}
}
